<?php

namespace Home\Controller;

use Common\Logic\UserLogic;
use Think\Controller;

/**
 * 外包客服外呼中心
 */
class CertUserController extends CommnController
{

    public function __construct()
    {
        parent::__construct();
    }

    //未借款用户列表
    public function cert_list()
    {
        $mod = new UserLogic();
        $data = $mod->getUserList();

//       var_dump($data);
        $this->assign(array(
            'data' => $data
//            'fpage' => $fpage,
//            'page_first' => $page->listfirst,
//            'tol' => $tol,
//            'kefu' => $kf
        ));

        $this->display();
        die;

        $search = I('user');
        //要12月份开始   认证通过的客户  给客服拨打电话
        $time_now = strtotime(date('Y-m-d', time()));
        $s_time = $time_now - 3 * 24 * 3600;
        $where = [];
//        if($_SESSION['id']!='20'){
//            $where['a.cert_time']=array('lt',$s_time);
//              }
        //一周前的时间戳
//        $week_time=time()-604800;\
        $week_time = strtotime(date('Y-m-d', time()));
        $where['a.cert_status'] = array('eq', 2);
        $where['b.vid'] = array('exp', 'is null');
        $where['c.vid'] = array('exp', 'is null');
        $where['a.type'] = array('neq', '2');
//        $where['c.ctime']=array('lt',$week_time);
        if (!empty($search)) {
            $where['a.truename|b.mobile'] = array('like', $search . '%');
        }

        $tol = M('user', '', 'USER_R')->join('a left join dxd_caiwu.user_borrow b on a.vid=b.vid')->join('left join dxd_kefu.kefu_ownuser c on a.vid=c.vid and c.type=1')->where($where)->count();
        $row = '30';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $data = M('user', '', 'USER_R')
            ->join('a left join dxd_caiwu.user_borrow b on a.vid=b.vid')
            ->join('left join dxd_kefu.kefu_ownuser c on a.vid=c.vid and c.type=1 and c.ctime>=' . $week_time)
            ->where($where)
            ->LIMIT($page->listfirst, $page->listRows)
            ->order('a.cert_time desc')
            ->field('a.vid,a.truename,a.ctime,a.mobile,a.sex,a.cert_time,a.type')
            ->select();
        foreach ($data as $k => $v) {
            if ($v['type'] == '1') {
                $data[$k]['type'] = '共享';
            } else if ($v['type'] == 3) {
                $data[$k]['type'] = '马上游呗';
            }
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            if (!empty($v['cert_time'])) {
                $data[$k]['cert_time'] = date('Y-m-d H:i', $v['cert_time']);
            } else {
                $data[$k]['cert_time'] = '--';
            }
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            if ($v['sex'] == 1) {
                $data[$k]['sex'] = '男';
            } else if ($v['sex'] == 2) {
                $data[$k]['sex'] = '女';
            } else if ($v['sex'] == 0) {
                $data[$k]['sex'] = '未知';
            }
        }
        //客服列表
        $where = [];
        $where['out_kf_id'] = 0;
        $where['status'] = 1;
        $where['part_id'] = 1;
        $where['role_id'] = 2;
        $kf = M('admin', '', 'KEFU')->where($where)->field('name,id as kf_id')->select();
        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'page_first' => $page->listfirst,
            'tol' => $tol,
            'kefu' => $kf
        ));

        $this->display();
    }

    //优质用户列表
    public function good_user_list()
    {
        $where = [];

        //优质用户 ：借款三次以上，逾期小于三天
//        $sub_sql='SELECT vid ,COUNT(vid) as num FROM dxd_caiwu.user_borrow WHERE is_success=2 and vid NOT IN ( SELECT vid FROM dxd_urge.user_overdue WHERE overdue_day > 3 GROUP BY vid ) GROUP BY vid HAVING num >3';
        $where['b.vid'] = array('exp', 'is null');
        $where['a.borrow_num'] = array('gt', 8);
        $where['a.three_overdue_num'] = array('elt', 0);
        $tol = M('user_borrow_statistics', '', 'USER_R')->join('a left join dxd_kefu.kefu_ownuser b on a.vid=b.vid and b.type=2 ')->where($where)->count();
        $row = '30';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $field = 'c.vid,c.truename,c.ctime,c.mobile,c.sex';
        $data = M('user_borrow_statistics', '', 'USER_R')->join('a left join dxd_kefu.kefu_ownuser b on a.vid=b.vid and b.type=2 ')->join(' join dxd_user.user c on a.vid=c.vid')->where($where)->LIMIT($page->listfirst, $page->listRows)->order('c.ctime desc')->field($field)->select();

        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            if ($v['sex'] == 1) {
                $data[$k]['sex'] = '男';
            } else if ($v['sex'] == 2) {
                $data[$k]['sex'] = '女';
            } else if ($v['sex'] == 0) {
                $data[$k]['sex'] = '未知';
            }
        }
        //客服列表
        $where = [];
        $where['out_kf_id'] = 0;
        $where['status'] = 1;
        $where['part_id'] = 1;
        $where['role_id'] = 2;
        $kf = M('admin', '', 'KEFU')->where($where)->field('name,id as kf_id')->select();

        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'page_first' => $page->listfirst,
            'tol' => $tol,
            'kefu' => $kf
        ));
        $this->display();
    }

    //认证未完成列表
    public function unfinish_cert()
    {
        //昨晚八点前的
        $end_time = strtotime(date('Y-m-d', time())) - 14400;
        $where['a.ctime'] = array('between', [1525104000, $end_time]);//18-5-1
        $where['b.vid'] = array('exp', 'is null');
        $where['a.cert_status'] = array('eq', 4);
        $tol = M('user', '', 'USER_R')->join('a left join dxd_kefu.kefu_ownuser b on b.vid=a.vid and b.type=5')->where($where)->count();
        $row = '30';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $data = M('user', '', 'USER_R')->join('a left join dxd_kefu.kefu_ownuser b on b.vid=a.vid and b.type=5')->field('a.id,a.vid,a.mobile,a.truename,a.ctime')->LIMIT($page->listfirst, $page->listRows)->order('a.id desc')->where($where)->select();

        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
        }
        //客服列表
        $where = [];
        $where['out_kf_id'] = 0;
        $where['status'] = 1;
        $where['part_id'] = 1;
        $where['role_id'] = 2;
        $kf = M('admin', '', 'KEFU')->where($where)->field('name,id as kf_id')->select();
        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'page_first' => $page->listfirst,
            'tol' => $tol,
            'kefu' => $kf
        ));
        $this->display();
    }

    //分给客服
    public function send_kefu()
    {
        $kf_id = I('kf_id');
        $type = I('type', 1);//1 未借款转化用户，2 优质用户,3 注册未认证
        $vids = I('vids');
        $arr = explode(',', $vids);
        $exit = array();//去重
        $add = array();
        $del_arr = [];
        $update_arr = array();
        for ($i = 0; $i < count($arr); $i++) {
            $has = M('kefu_ownuser', '', 'KEFU')->where(['vid' => $arr[$i], 'type' => $type])->field(['id'])->find();
            if (!empty($has)) {
                $del_arr[] = $has['id'];
//                $update_arr[]=array('id'=>$has['id'],'admin_id'=>$kf_id,'ctime'=>time());
//                $update=M('kefu_ownuser', '', 'KEFU')->where(['vid' => $arr[$i],'type'=>$type])->setField('admin_id',$kf_id);
            }
//            else if(empty($has) && !in_array($arr[$i],$exit)){
            $add[] = array(
                'vid' => $arr[$i],
                'ctime' => time(),
                'admin_id' => $kf_id,
                'type' => $type
            );
            $exit[] = $arr[$i];
//            }

        }
        if (!empty($del_arr) && $type == '1') {
            M('kefu_ownuser', '', 'KEFU')->where(['id' => array('in', $del_arr), 'type' => 1])->delete();
        }

        if (empty($add)) {
//            $this->ajaxReturn(array('result'=>'','add'=>$add,'update'=>$update));
            $this->ajax('1001', '派发成功');
            die;
        }

        if (M('kefu_ownuser', '', 'KEFU')->AddAll($add)) {
//            $this->ajaxReturn(array('result'=>'','add'=>$add,'update'=>$update));
            $this->ajax('1001', '派发成功');
            die;
        }
    }

    //未借款分配统计
    public function no_borrow_statics()
    {
        // 99 70  67
        $where = [];
        $where['part_id'] = array('eq', 1);//
        $where['status'] = array('eq', 1);//
        $where['out_kf_id'] = array('eq', 0);//
        $where['role_id'] = array('eq', 2);//
        $admin = M('admin', '', 'KEFU')->where($where)->field('id,name')->select();
        foreach ($admin as $k => $v) {
            //总人数
            $admin[$k]['user_total_num'] = M('kefu_ownuser', '', 'KEFU')->where(['admin_id' => $v['id'], 'type' => 1])->count();
            $w = [];
            $w['a.admin_id'] = $v['id'];
            $w['a.type'] = 1;
            $w['b.vid'] = array('exp', 'is null');
            //未借款人数
            $admin[$k]['user_no_borrow_num'] = M('kefu_ownuser', '', 'KEFU')->join('a left join dxd_caiwu.user_borrow b on a.vid=b.vid')->where($w)->count();
        }
        $this->assign(array(
            'admin' => $admin
        ));

        $this->display();


    }

    /**
     * 三天未借款的用户   无借款，无等待时间，用户状态正常
     */
    public function long_time_no_borrow()
    {
//        $week_time = strtotime(date('Y-m-d', time()));
        $where['c.vid'] = array('exp', 'is null');
        $where['a.last_btime'] = array('lt', time() - 3 * 86400);
//        $where['d.status'] = array('notin', [1,3]);
        $tol = M('temp_long_borrow', '', 'KEFU')
            ->join('a join dxd_user.user b on b.vid=a.vid and b.type!=2 and b.cert_status=2 and b.quota>0')
//            ->join('join dxd_caiwu.user_borrow d on d.vid=a.vid')
            ->join('left join dxd_kefu.kefu_ownuser c on c.vid=a.vid and c.type=6')
            ->where($where)
            ->count();
        $row = '30';
        $page = new PageController($tol, $row);

        $fpage = $page->fpage();
        $this->data = M('temp_long_borrow', '', 'KEFU')
            ->join('a join dxd_user.user b on b.vid=a.vid and b.type!=2 and b.cert_status=2 and b.quota>0')
//            ->join('join dxd_caiwu.user_borrow d on d.vid=a.vid and d.status not in (1,3)')
            ->join('left join dxd_kefu.kefu_ownuser c on c.vid=a.vid and c.type=6')
            ->where($where)
            ->LIMIT($page->listfirst, $page->listRows)
            ->field('a.vid,b.truename,b.mobile,FROM_UNIXTIME(a.last_btime,\'%y-%m-%d %h:%i\') as cert_time')
            ->order('a.last_btime desc')
            ->select();
//        var_dump($this->data);
        $where = [];
        $where['out_kf_id'] = 0;
        $where['status'] = 1;
        $where['part_id'] = 1;
        $where['role_id'] = 2;
        $this->kefu = M('admin', '', 'KEFU')->where($where)->field('name,id as kf_id')->select();
        $this->assign(array(
            'fpage' => $fpage,
            'tol' => $tol,
        ));
        $this->display();

    }

    /**
     * excel上传
     */
    public function data_export()
    {

        $tol = M('outer_call', '', 'KEFU')->count();
//        $tol = count($sum);
        $row = '30';
        $page = new PageController($tol, $row);
        $fpage = $page->fpage();
        $data = M('outer_call', '', 'KEFU')->LIMIT($page->listfirst, $page->listRows)->order('id desc')->field('phone,ctime,type')->select();
        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
        }
        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'tol' => $tol
        ));
        $this->display();
    }

    public function upload()
    {
        ini_set('memory_limit', '512M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls','csv'),
                'maxSize' => 8145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);
            if (!$info = $upload->upload()){
                $this->error($upload->getError());
            }
            require_once './Public/admin/excel/PHPExcel.php'; //导入php文件
            $file_name = $upload->rootPath . $info['photo']['savepath'] . $info['photo']['savename'];
            $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式

            if ($extension == 'xlsx'){
                $PHPReader = new \PHPExcel_Reader_Excel2007();        //建立reader对象
                if(!$PHPReader->canRead($file_name)){
                   $PHPReader = new \PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($file_name)){
                  echo 'no Excel';
                  return ;
                }
          }
                $objPHPExcel = $PHPReader->load($file_name);
//                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
//                $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                var_dump(333);die;

            } else if ($extension == 'xls') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
            }else if($extension=='csv'){
                 $file=fopen($file_name,'r');
                 $add_arr=[];
                $row=1;
                $type=0;
                $times=0;
                while ($data=fgetcsv($file,5000,',')){
                     if($row==1){
                        $type=$data[1];
                        $times=$data[2];
                    }
                     $row ++;
                         if(strlen($data[0])>=11){
                            $row_data['phone']=$data[0];
                            $row_data['ctime']=time();
                            $row_data['type']=$type;
                            $row_data['times']=$times;
                            $add_arr[]=$row_data;
                        }
                }
                M('outer_call', '', 'KEFU')->addAll($add_arr);
                unlink($file_name);

//                var_dump($add_arr);
                die;

            }

            $sheet = $objPHPExcel->getSheet(0);

            $highestRow = $sheet->getHighestRow();//取得总行数
            //上传的类型
            $cell = $objPHPExcel->getActiveSheet()->getCell("B1")->getValue();

            $times = $objPHPExcel->getActiveSheet()->getCell("C1")->getValue();
            switch ($cell) {
                case 'one':
                    $type = 1;
                    break;
                case 'two':
                    $type = 2;
                    break;
                case 'three':
                    $type = 3;
                    break;
                case 'four':
                    $type = 4;
                    break;
                case 'five':
                    $type = 5;
                    break;
                case 'six':
                    $type = 6;
                    break;
                case 'seven':
                    $type = 7;
                    break;
                default:
                    $type = 1;
                    break;
            }

            $add_arr = [];
            for ($i = 2; $i <= $highestRow; $i++) {
//看这里看这里,前面小写的a是表中的字段名，后面的大写A是excel中位置
                $phone = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();
                if (strlen($phone) >= 11) {
                    $data['phone'] = $phone;
                    $data['ctime'] = time();
                    $data['type'] = $type;
                    $data['times'] = $times;
                    $add_arr[] = $data;
                }
            }
             M('outer_call', '', 'KEFU')->addAll($add_arr);
            $this->success('导入成功!');
            unlink($file_name);

        } else {
            $this->error("请选择上传的文件");
        }

    }

}